﻿using System;
using System.IO;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using Wala.Connection.Encrypts;
using Wala.Connection.Helpers;
using Wala.Connection.Objects.Authen;
using Wala.Infrastructure;

namespace Wala.Connection.HttpsConnections
{
    public class ClientHttpsRequest
    {
        //auth.wala.vn
        private static string SALT_URL = "https://auth.wala.vn/auth?action=getsalt&user=";
        private static string TOKEN_URL = "https://auth.wala.vn/auth?action=gettok&user={0}&hashkey={1}";
        private static string FORGETPASS_CODE = URLConstant.HOST_SECURE+"/wala-register/wala-register/forget-password?phone={0}";

        public static async Task<string> GetForgetPassCode(string phone)
        {
		    string str = string.Format(FORGETPASS_CODE, phone);
		    return await HttpsRequest(str);
	    }

        public static async Task<string> GenerateNewPassword(string phone, string password, string verifyCode)
        {
            string str = URLConstant.HOST_SECURE + "/wala-register/wala-register/new-password";
            string content = "";
            try
            {
                password = Encrypt.EncryptMD5(password);

                HttpWebRequest webRequest = (HttpWebRequest)HttpWebRequest.Create(str);
                webRequest.Method = "POST";
                webRequest.ContentType = "application/x-www-form-urlencoded";
                string data = String.Format("phone={0}&code={1}&newPassword={2}",
                                                    Uri.EscapeUriString(phone),
                                                    Uri.EscapeUriString(verifyCode),
                                                    Uri.EscapeUriString(password));
                byte[] contentInBytes = Encoding.UTF8.GetBytes(data);

                using (Stream requestStream = await webRequest.GetRequestStreamAsync())
                    requestStream.Write(contentInBytes, 0, contentInBytes.Length);

                WebResponse response = await webRequest.GetResponseAsync();
                StreamReader requestReader = new StreamReader(response.GetResponseStream());
                content = requestReader.ReadToEnd();
            }
            catch (Exception ex)
            {
                content = "Error: " + ex.Message;
            }
            return content;
        }

        public static async Task<string> GetVerifyCode(string phone)
        {
            string str = "https://secure.wala.vn/wala-register/wala-register/getcode?phone=" + Uri.EscapeUriString(phone);
            return await HttpsRequest(str);
        }

        public static async Task<string> GenerateUserAccount(string phone, string verifyCode, string password, string displayName)
        {
            string str = "https://secure.wala.vn/wala-register/wala-register/register";
            string content = "";
            try
            {                
                password = Encrypt.EncryptMD5(password);

                HttpWebRequest webRequest = (HttpWebRequest)HttpWebRequest.Create(str);
                webRequest.Method = "POST";
                webRequest.ContentType = "application/x-www-form-urlencoded";
                string data = String.Format("phone={0}&password={1}&code={2}&displayName={3}",
                                                    Uri.EscapeUriString(phone),
                                                    Uri.EscapeUriString(password),
                                                    Uri.EscapeUriString(verifyCode),
                                                    Uri.EscapeUriString(displayName)
                                                    );
                byte[] contentInBytes = Encoding.UTF8.GetBytes(data);

                using (Stream requestStream = await webRequest.GetRequestStreamAsync())
                    requestStream.Write(contentInBytes, 0, contentInBytes.Length);

                WebResponse response = await webRequest.GetResponseAsync();
                StreamReader requestReader = new StreamReader(response.GetResponseStream());
                content = requestReader.ReadToEnd();
            }
            catch (Exception ex)
            {
                content = ex.Message;
            }
            return content;
        }

        /// <summary>
        /// Get salt key json string
        /// </summary>
        /// <param name="userName"></param>
        /// <returns></returns>
        public static async Task<string> GetSalt(string userName)
        {
            string str = SALT_URL + Uri.EscapeUriString(userName);
            return await HttpsRequest(str);
        }
        
        /// <summary>
        /// Get token json strings
        /// </summary>
        /// <param name="userName"></param>
        /// <param name="passHash"></param>
        /// <returns></returns>
        public static async Task<string> GetToken(string userName, string passHash)
        {
            string str = String.Format(TOKEN_URL, Uri.EscapeUriString(userName), Uri.EscapeUriString(passHash));            
            return await HttpsRequest(str);
        }

        /// <summary>
        /// Get json string result from response
        /// </summary>
        /// <param name="url"></param>
        /// <returns></returns>
        public static async Task<string> HttpsRequest(string url)
        {
            string content = "";
            try
            {
                string timeStamp = DateTime.Now.Ticks.ToString("x");
                url = url + "&timestamp=" + timeStamp;
                HttpWebRequest request = HttpWebRequest.CreateHttp(url);                 
                HttpWebResponse webResponse = await request.GetResponseAsync() as HttpWebResponse;
                Stream responseStream = webResponse.GetResponseStream();

                using (StreamReader reader = new StreamReader(responseStream))
                {
                    content = await reader.ReadToEndAsync();
                }
            }
            catch (Exception ex)
            { 
                
            }
            return content;
        }

        /// <summary>
        /// Send an location request and get an json result string
        /// </summary>
        /// <param name="queryUri"></param>
        /// <param name="userId"></param>
        /// <param name="token"></param>
        /// <param name="version"></param>
        /// <returns></returns>
        public static async Task<string> LocationRequest(string queryUri, string userId, string token)
        {
            string url = URLConstant.HOST_SECURE + queryUri;
            string content = "";
            try
            {
                HttpWebRequest request = HttpWebRequest.CreateHttp(url);
                request.CookieContainer = new CookieContainer();
                request.CookieContainer.Add(new Uri(url), new Cookie("uid", userId));
                request.CookieContainer.Add(new Uri(url), new Cookie("token", token));                

                HttpWebResponse webResponse = await request.GetResponseAsync() as HttpWebResponse;
                Stream responseStream = webResponse.GetResponseStream();

                using (StreamReader reader = new StreamReader(responseStream))
                {
                    content = await reader.ReadToEndAsync();
                }
            }
            catch (Exception ex)
            {

            }
            return content;
        }

        /// <summary>
        /// Send an https Get request with cookies which contains uid and token
        /// </summary>
        /// <param name="url"></param>
        /// <returns></returns>
        public static async Task<string> HttpsRequestWithCookie(string url)
        {
            string content = "";
            try
            {
                string timeStamp = DateTime.Now.Ticks.ToString("x");
                url = url + "&timestamp=" + timeStamp;

                HttpWebRequest request = HttpWebRequest.CreateHttp(url);

                var objectStorageHelper = new StorageHelper<RetAuthen>(StorageType.Local);
                RetAuthen statsDetails = await objectStorageHelper.LoadASync("RetAuthen");

                string uid = statsDetails.User.Id.ToString();
                string token = statsDetails.User.Token;
                string version = "1.0";
                request.CookieContainer = new CookieContainer();
                request.CookieContainer.Add(new Uri(url), new Cookie("uid", uid));
                request.CookieContainer.Add(new Uri(url), new Cookie("token", token));
                request.CookieContainer.Add(new Uri(url),new Cookie("version",version));
                
                HttpWebResponse webResponse = await request.GetResponseAsync() as HttpWebResponse;
                Stream responseStream = webResponse.GetResponseStream();

                using (StreamReader reader = new StreamReader(responseStream))
                {
                    content = await reader.ReadToEndAsync();
                }
            }
            catch (Exception ex)
            {
                string message = ex.Message;
            }
            return content;
        }        
    }
}
